package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.redisson.client.protocol.decoder.FastAutoClaimDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;


@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Override
    public Result queryBlogById(Long blogId) {
        //查询博客
        Blog blog = this.getById(blogId);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }

        //获取博客的用户并设置图像和昵称
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        //判断当前用户是否已经点赞了，并且设置islike字段
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    //判断当前用户是否点赞了该博客笔记 用redis中的set集合（需要遍历所有）或string（i）/zset 时间排序
    public void isBlogLiked(Blog blog) {
        Long userId = UserHolder.getUser().getId();
        //key为当前博客的id
        String key = BLOG_LIKED_KEY + blog.getId();
        Double isLike = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (isLike != null) {
            blog.setIsLike(true);
        }
    }

    //使用zset保存点赞的所有用户
    @Override
    public Result likeOrCancel(Long id) {
        Long userId = UserHolder.getUser().getId();
        String key = BLOG_LIKED_KEY + id;
        //如果当前用户点过赞，则取消并设置博客总赞数-1
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score != null) {
            LambdaUpdateWrapper<Blog> UpdateWrapper = new LambdaUpdateWrapper<Blog>()
                    .eq(Blog::getId, id).setSql("liked = liked - 1");
            boolean result = this.update(UpdateWrapper);
            //如果数据库更新成功，则更新缓存
            if (result) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
                return Result.ok();
            }
            return Result.fail("取消失败");
        }
        //之前未点赞，点赞并设置博客赞数+1 并设置分数为当前时间
        boolean result = this.update(new LambdaUpdateWrapper<Blog>().eq(Blog::getId, id).setSql("liked = liked + 1"));
        if (result) {
            stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            return Result.ok();
        }
        return Result.fail("点赞失败");
    }

    //查询top5的点赞
    @Override
    public Result queryUsersLikeById(Long id) {
        //根据博客id查询点赞top5的用户
        String key = BLOG_LIKED_KEY + id;
        Set<String> userSet = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(userSet == null || CollUtil.isEmpty(userSet)){
            return  Result.ok(Collections.emptyList());
        }
        //将字符串转为Long
        List<Long> userIds = userSet.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", userIds);
        // 根据id降序排序 select * from tb_user where id in(1,5) order by field(id, 1, 5) 数据库默认按照主键自增的顺序查询 自定义排序
        List<UserDTO> userDTOList = userService.list(new LambdaQueryWrapper<User>()
                        .in(User::getId, userIds)
                        .last("order by field (id," + idStr + ")"))
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOList);
    }

    //滚动分页
    @Override
    public Result scroll(Long lastMinTime, Long offset) {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //拼接key
        String key = FEED_KEY + userId;
        //查询当前用户推送箱（关注的用户发送动态）
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                        .reverseRangeByScoreWithScores(key, 0, lastMinTime, offset, 2);

        //3.非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }

        //博客的id
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        //本次查询最小分数（时间）
        Long minTime = 0L;
        //本次查询最小分数相同的元素的个数 最少为1个
        Integer os = 1;
        //遍历元组，设置这次最小的时间和offset 返回给前端
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {  //假设score: 5 4 4 2 2 1
            // 添加博客id到集合中
            blogIds.add(Long.valueOf(typedTuple.getValue()));
            long time = typedTuple.getScore().longValue();
            if (time == minTime) { //相等加一
                os++;
            } else {
                minTime = time; //不等 直接复制 因为后面的元素时间肯定比前面小的
                os = 1;  //重置
            }
        }

        //5.根据id查询blog
        String idStr = StrUtil.join(",", blogIds);
        List<Blog> blogs = query().in("id", blogIds)
                .last("ORDER BY FIELD(id," + idStr + ")")  //按照集合的顺序查询返回
                .list();
        for (Blog blog : blogs) {
            queryBlogUser(blog);
            //判断是否已经给当前博客点赞
            //如果已经点赞给isliked字段设置为true
            isBlogLiked(blog);
        }
        //6.封装并返回
        ScrollResult result = new ScrollResult();
        result.setList(blogs);
        result.setOffset(os);
        result.setMinTime(minTime);
        return Result.ok(result);


    }

    private void queryBlogUser(Blog blog) {

    }
}
